package org.example.seckillsample.controller;

import com.fasterxml.jackson.databind.util.JSONPObject;
import org.example.seckillsample.entity.Commodity;
import org.example.seckillsample.service.SecKillService;
import org.example.seckillsample.sto.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
public class SecKillController {

    @Autowired
    SecKillService secKillService;

    @GetMapping("list")
    public Result getAllCommodity(){
        List<Commodity> list = secKillService.findAll();

        Result result =  Result.ok().data("commodityList",list);

        return result;
    }

    @GetMapping("/findById")
    public Result findById(@RequestParam("id") Long id){
        Commodity commodity = secKillService.findById(id);
        return Result.ok().data("commodity",commodity);
    }

    @PostMapping("/buy")
    public Result buy(@RequestBody Map<String, Object> request){
        System.out.println(request);

        Long commodityId;
        String money;
        String phone;
        if (request.containsKey("id")){
            commodityId = Long.parseLong(Objects.toString(request.get("id")));
        }else{
            commodityId = null;
        }

        if (request.get("money")!= null){
            money = Objects.toString(request.get("money"));
        }else{
            money = null;
        }

        if (request.get("phone")!= null){
            phone = Objects.toString(request.get("phone"));
        }else{
            phone = null;
        }
        if(secKillService.buy(commodityId,money,phone)){
            return Result.ok();
        }else{
            return Result.error();
        }
    }
    @RequestMapping("a")
    public String a(){
        return "aaaa";
    }
}
